<script setup>
import { reactive, ref, computed, nextTick, onMounted } from 'vue'
import {
  PlusOutlined,
  PlayCircleOutlined,
  EyeOutlined,
  DeleteOutlined
} from '@ant-design/icons-vue'
import { message } from 'ant-design-vue'
import axios from 'axios'

const formState = reactive({
  //基础信息
  title: '',
  //配套设施
  provinceId: undefined,
  //省份
  districtId: undefined,
  //城市
  cityId: undefined,
  //房屋样式
  layout: undefined,
  //配套设施
  facilityIds: [],
  //详细介绍
  description: '',
  //联系方式
  phone: '',
  //房源照片/视频
  files: [],
  //房源标签
  labels: [],
  //房屋面积
  area: undefined,
  //月租金
  rent: undefined,
  //所在楼层
  floor: undefined,
  //租约方式
  rentalMethod: undefined,
  //朝向
  orientation: undefined,
  //装修
  decoration: undefined,
})

const rules = {
  title: [{ required: true, message: '请输入房源标题' }],
  phone: [{ required: true, message: '请输入联系电话' }],
  description: [{ required: true, message: '请输入房源描述' }],
  area: [{ required: true, message: '请输入房屋面积' }],
  rent: [{ required: true, message: '请输入月租金' }],
  floor: [{ required: true, message: '请输入所在楼层' }]
}

const facilitiesOptions = ref([])

const getFacilities = async () => {
  try {
    const response = await axios.get(`${window.link}/landlord/release/facilities`, {
      headers: {
        'access-token': localStorage.getItem('access-token')
      }
    })
    if (response.data.code === 200) {
      // 修改为使用 id 作为 value
      facilitiesOptions.value = response.data.data.map(item => ({
        label: item.name,
        value: item.id  // 使用 id 作为 value 而不是 name
      }))
    } else {
      message.error(response.data.message)
    }
  } catch (error) {
    message.error('获取设施选项失败：' + error.message)
  }
}

onMounted(() => {
  getFacilities()
})
//详情内容
//文件列表
const fileList = ref([])
//预览
const previewVisible = ref(false)
//预览地址
const previewUrl = ref('')
//预览标题
const previewTitle = ref('')
//是否为视频
const isPreviewVideo = ref(false)
//房型结构
const layoutOptions = ref(['一室一厅', '两室一厅', '两室两厅', '三室一厅', '三室两厅', '四室一厅', '四室两厅', '五室两厅', '复式', '别墅', '单间', '开间'])
//租约方式
const leaseTypeOptions = ref(['整租', '合租'])
//朝向
const orientationOptions = ref(['东', '南', '西', '北', '东南', '东北', '西南', '西北'])
//装修
const decorationOptions = ref(['精装', '简装','豪华装修','毛坯'])
//标签
const labelOptions = ref([
  { label: '精装公寓', value: 0 },
  { label: '地铁房源', value: 1 },
  { label: '品质豪宅', value: 2 },
  { label: '优质合租', value: 3 },
  { label: '商铺办公', value: 4 }
])
//地址
const provinces = ref([])
const cities = ref([])
const districts = ref([])
// 判断是否为视频文件
const isVideo = (file) => {
  const fileType = file.type || ''
  const fileName = file.name || ''
    return fileType.startsWith('video/') ||   // MIME 类型
           fileName.match(/\.(mp4|mov)$/i)
}

// 上传前校验
const beforeUpload = (file) => {
  // 检查文件类型
  const isImage = file.type.startsWith('image/')    // MIME 类型
  const isVideoFile = file.type.startsWith('video/')

  if (!isImage && !isVideoFile) {
    message.error('只能上传图片或视频文件！')
    return false
  }
  // 检查视频大小
  if (isVideoFile) {
    const isLt50M = file.size / 1024 / 1024 < 50
    if (!isLt50M) {
      message.error('视频必须小于 50MB!')
      return false
    }
  }
  // 检查图片大小
  if (isImage) {
    const isLt5M = file.size / 1024 / 1024 < 5
    if (!isLt5M) {
      message.error('图片必须小于 5MB!')
      return false
    }
  }
  // 检查文件总数
  if (fileList.value.length >= 8) {
    message.error('最多只能上传8个文件！')
    return false
  }
  return true
}

const handleChange = async (info) => {
  const { file, fileList: newFileList } = info

  // 限制上传数量
  if (newFileList.length > 8) {
    message.warning('最多只能上传8个文件')
    return
  }

  // 处理每个文件的预览
  const updatedFileList = await Promise.all(newFileList.map(async (f) => {
    if (!f.preview && f.originFileObj) {
      if (isVideo(f)) {
        // 为视频生成预览URL
        f.preview = URL.createObjectURL(f.originFileObj)
      } else {
        // 为图片生成预览URL
        f.preview = await getBase64(f.originFileObj)
      }
    }
    return f
  }))

  fileList.value = updatedFileList

  // 处理上传状态
  if (file.status === 'done') {
    message.success(`${file.name} 上传成功`)
  } else if (file.status === 'error') {
    message.error(`${file.name} 上传失败`)
  }
}

// 预览文件
const handlePreview = async (file) => {
  if (!file.url && !file.preview && file.originFileObj) {
    if (isVideo(file)) {
      file.preview = URL.createObjectURL(file.originFileObj)
    } else {
      file.preview = await getBase64(file.originFileObj)
    }
  }
  previewUrl.value = file.url || file.preview
  previewVisible.value = true
  previewTitle.value = file.name
  isPreviewVideo.value = isVideo(file)
}

// 关闭预览
const handlePreviewCancel = () => {
  previewVisible.value = false
  previewUrl.value = ''
}

// 删除文件
const handleRemove = (file) => {
  const index = fileList.value.indexOf(file)
  const newFileList = fileList.value.slice()
  newFileList.splice(index, 1)
  fileList.value = newFileList
}

// 将文件转换为 Base64
const getBase64 = (file) => {
  return new Promise((resolve, reject) => {
    const reader = new FileReader()
    reader.readAsDataURL(file)
    reader.onload = () => resolve(reader.result)
    reader.onerror = error => reject(error)
  })
}

const onFinish = async (values) => {
  try {
    // 构建媒体文件的 FormDatas
    const mediaFormData = new FormData()
    fileList.value.forEach((file, index) => {
      if (file.originFileObj) {
        // 添加文件类型标识
        const fileType = isVideo(file) ? 'video' : 'image'
        mediaFormData.append('fileTypes', fileType)
        mediaFormData.append('files', file.originFileObj)
      }
    })

    // 构建其他表单数据的 JSON 对象
    const jsonData = {}
    Object.keys(formState).forEach(key => {
      if (formState[key] !== undefined &&
          formState[key] !== '' &&
          key !== 'files') {  // 排除文件相关字段
        jsonData[key] = formState[key]
      }
    })

    // 先上传媒体文件
    const mediaResponse = await axios.post(`${window.link}/user/file/upload`, mediaFormData, {
      headers: {
        'Content-Type': 'multipart/form-data',
        'access-token': localStorage.getItem('access-token')
      }
    })
    if (mediaResponse.data.code !== 200) {
      message.error(mediaResponse.data.message)
      return
    }
    console.log(mediaResponse);
    // 获取媒体文件的访问路径
    const mediaUrls = mediaResponse.data.data
    jsonData.files = mediaUrls
    console.log(jsonData);
     // 将媒体文件路径添加到 JSON 数据中

    // 发送其他表单数据
    console.log(jsonData);
    const response = await axios.post(`${window.link}/landlord/release`, jsonData, {
      headers: {
        'access-token': localStorage.getItem('access-token')
      }
    })
    if (response.data.code === 200) {
      message.success('发布成功')
      // 重置表单数据
      Object.keys(formState).forEach(key => {
        if (Array.isArray(formState[key])) {
          formState[key] = []
        } else {
          formState[key] = undefined
        }
      })
      // 清空文件列表
      fileList.value = []
      // 清空标签输入
      formState.labels = []
      // 清空设施输入
      formState.facilityIds = []
      // 重置预览状态
      previewVisible.value = false
      previewUrl.value = ''
      previewTitle.value = ''
      isPreviewVideo.value = false
    }
  } catch (error) {
    console.error('发布失败：' + error.message);
  }
}



// 获取省份和城市数据
const getProvinces = async () => {
  try {
    const response = await axios.get(`${window.link}/location/province`, {
      headers: {
        'access-token': localStorage.getItem('access-token')
      }
    })
    if (response.data.code === 200) {
      // 假设后端返回的数据包含 provinces 和 cities
      provinces.value = response.data.data
      cities.value = response.data.data.cities
      console.log(cities.value);
      console.log(provinces.value);

    }
  } catch (error) {
    message.error('获取地址数据失败：' + error.message)
  }
}

// 获取区域数据
const getDistricts = async (cityId) => {
  if (!cityId) return
  try {
    const response = await axios.get(`${window.link}/location/district/${cityId}`, {
      headers: {
        'access-token': localStorage.getItem('access-token')
      }
    })
    if (response.data.code === 200) {
      districts.value = response.data.data
      formState.district = undefined // 清空已选区域
    }
  } catch (error) {
    message.error('获取区域数据失败：' + error.message)
  }
}
// 监听省份变化
const handleProvinceChange = (value) => {
  formState.cityId = undefined // 清空已选城市
  formState.districtId = undefined // 清空已选区域
  districts.value = [] // 清空区域列表
  cities.value = provinces.value.find(province => province.provinceId === value).cities
}

// 监听城市变化
const handleCityChange = (value) => {
  getDistricts(value)

}

// 组件挂载时获取省份和城市数据
onMounted(() => {
  getProvinces()
})

</script>
<template>
  <div class="release-container">
    <a-form
      :model="formState"
      :rules="rules"
      layout="vertical"
      @finish="onFinish"
    >
      <!-- 基础信息 -->
      <a-card title="基础信息" class="section-card">
        <a-form-item label="房源标题" name="title">
          <a-input
            v-model:value="formState.title"
            placeholder="请输入标题"
          />
        </a-form-item>

        <a-form-item label="房源标签" name="labels">
          <a-select
            v-model:value="formState.labels"
            mode="multiple"
            style="width: 100%"
            placeholder="请选择房源标签"
            :options="labelOptions"
          />
        </a-form-item>

        <a-form-item label="房源地址">
          <a-space>
            <a-select
              v-model:value="formState.provinceId"
              style="width: 120px"
              placeholder="省"
              @change="handleProvinceChange"
            >
              <a-select-option
                v-for="province in provinces"
                :key="province.provinceId"
                :value="province.provinceId"
              >
                {{ province.provinceName }}
              </a-select-option>
            </a-select>
            <a-select
              v-model:value="formState.cityId"
              style="width: 120px"
              placeholder="市"
              @change="handleCityChange"
            >
              <a-select-option
                v-for="city in cities"
                :key="city.id"
                :value="city.id"
              >
                {{ city.name }}
              </a-select-option>
            </a-select>
            <a-select
              v-model:value="formState.districtId"
              style="width: 120px"
              placeholder="区"
            >
              <a-select-option
                v-for="district in districts"
                :key="district.id"
                :value="district.id"
              >
                {{ district.name }}
              </a-select-option>
            </a-select>
          </a-space>
        </a-form-item>

        <a-form-item label="房屋面积" name="area">
          <a-input-number
            v-model:value="formState.area"
            :min="1"
            :max="1000"
            addon-after="平方米"
            style="width: 200px"
          />
        </a-form-item>

        <a-form-item label="月租金" name="rent">
          <a-input-number
            v-model:value="formState.rent"
            :min="1"
            :precision="2"
            addon-after="元/月"
            style="width: 200px"
          />
        </a-form-item>

        <a-form-item label="所在楼层" name="floor">
          <a-input-number
            v-model:value="formState.floor"
            :min="1"
            :max="100"
            style="width: 200px"
            placeholder="请输入所在楼层"
          />
        </a-form-item>

        <a-form-item label="房型结构">
          <a-space>
            <a-select
              v-model:value="formState.layout"
              style="width: 120px"
              placeholder="请选择房型"
            >
              <a-select-option
                v-for="(layout,index) in layoutOptions"
                :key="index"
                :value= index
              >
                {{ layout }}
              </a-select-option>
            </a-select>
          </a-space>
        </a-form-item>

        <a-form-item label="租约方式">
          <a-select
            v-model:value="formState.rentalMethod"
            style="width: 120px"
            placeholder="请选择租约方式"
          >
            <a-select-option
              v-for="(type, index) in leaseTypeOptions"
              :key="index"
              :value="index"
            >
              {{ type }}
            </a-select-option>
          </a-select>
        </a-form-item>

        <a-form-item label="朝向">
          <a-select
            v-model:value="formState.orientation"
            style="width: 120px"
            placeholder="请选择朝向"
          >
            <a-select-option
              v-for="(orientation, index) in orientationOptions"
              :key="index"
              :value="index"
            >
              {{ orientation }}
            </a-select-option>
          </a-select>
        </a-form-item>

        <a-form-item label="装修">
          <a-select
            v-model:value="formState.decoration"
            style="width: 120px"
            placeholder="请选择装修情况"
          >
            <a-select-option
              v-for="(decoration, index) in decorationOptions"
              :key="index"
              :value="index"
            >
              {{ decoration }}
            </a-select-option>
          </a-select>
        </a-form-item>
      </a-card>

      <!-- 配套设施 -->
      <a-card title="配套设施" class="section-card">
        <a-space wrap>
          <a-checkbox-group
            v-model:value="formState.facilityIds"
            :options="facilitiesOptions"
          />
        </a-space>
      </a-card>

      <!-- 详细介绍 -->
      <a-card title="详细介绍" class="section-card">
        <a-form-item name="description">
          <a-textarea
            v-model:value="formState.description"
            :rows="4"
            placeholder="请输入房源描述，如房屋亮点、周边配套等信息"
          />
        </a-form-item>
      </a-card>

      <!-- 房源照片/视频 -->
      <a-card title="房源照片/视频" class="section-card">
        <a-form-item name="media">
          <a-upload-dragger
            v-model:fileList="fileList"
            name="file"
            :customRequest="() => {}"
            :action="undefined"
            :multiple="true"
            list-type="picture-card"
            :accept="'.jpg,.jpeg,.png,.mp4,.mov'"
            :before-upload="beforeUpload"
            @change="handleChange"
            @preview="handlePreview"
          >

            <div v-if="fileList.length < 8">
              <p class="ant-upload-drag-icon">
                <plus-outlined />
              </p>
              <p class="ant-upload-text">点击或拖拽上传</p>
              <p class="ant-upload-hint">支持图片和视频格式，单个视频不超过50MB</p>
            </div>
          </a-upload-dragger>

          <!-- 媒体文件列表 -->
          <div class="media-list">
            <div v-for="(file, index) in fileList" :key="index" class="media-item">
              <!-- 视频预览 -->
              <div v-if="isVideo(file)" class="media-preview video-preview">
                <video
                  :src="file.preview || file.url"
                  class="preview-content"
                ></video>
                <div class="play-icon">
                  <play-circle-outlined />
                </div>
              </div>
              <!-- 图片预览 -->
              <div v-else class="media-preview image-preview">
                <img
                  :src="file.preview || file.url"
                  :alt="file.name"
                  class="preview-content"
                />
              </div>
              <!-- 操作按钮 -->
              <div class="media-actions">
                <eye-outlined class="action-icon" @click="handlePreview(file)" />
                <delete-outlined class="action-icon" @click="handleRemove(file)" />
              </div>
            </div>
          </div>
        </a-form-item>

        <!-- 预览模态框 -->
        <a-modal
          :visible="previewVisible"
          :title="previewTitle"
          :footer="null"
          @cancel="handlePreviewCancel"
          :width="isPreviewVideo ? '800px' : '600px'"
        >
          <video
            v-if="isPreviewVideo"
            :src="previewUrl"
            controls
            style="width: 100%"
          ></video>
          <img
            v-else
            :src="previewUrl"
            style="width: 100%"
            :alt="previewTitle"
          />
        </a-modal>
      </a-card>

      <!-- 联系方式 -->
      <a-card title="联系方式" class="section-card">
        <a-form-item label="联系电话" name="phone">
          <a-input v-model:value="formState.phone" style="width: 200px" />
        </a-form-item>
      </a-card>

      <!-- 提交按钮 -->
      <div class="submit-container">
        <a-button type="primary" html-type="submit" size="large">发布房源</a-button>
      </div>
    </a-form>
  </div>
</template>


<style scoped>
.release-container {
  max-width: 1000px;
  margin: 0 auto;
  padding: 24px;
}

.section-card {
  margin-bottom: 24px;
}

.upload-box, .qrcode-box {
  text-align: center;
  min-height: 200px;
  padding: 20px;
  border: 1px dashed #d9d9d9;
  border-radius: 8px;
  background: #fafafa;
}

.qrcode-box img {
  max-width: 150px;
  margin-bottom: 12px;
}

.submit-container {
  text-align: center;
  margin-top: 40px;
}

:deep(.ant-upload-drag) {
  height: 200px;
}

:deep(.ant-upload-list-picture-card-container) {
  width: 104px;
  height: 104px;
  margin: 0 8px 8px 0;
}

:deep(.ant-upload-list-picture-card .ant-upload-list-item) {
  padding: 0;
}

:deep(.ant-upload.ant-upload-select-picture-card) {
  width: 104px;
  height: 104px;
  margin: 0 8px 8px 0;
}

:deep(.ant-upload-drag) {
  height: auto;
  min-height: 104px;
}

.media-list {
  display: flex;
  flex-wrap: wrap;
  gap: 8px;
  margin-top: 16px;
}

.media-item {
  position: relative;
  width: 104px;
  height: 104px;
  border: 1px solid #d9d9d9;
  border-radius: 8px;
  overflow: hidden;
}

.media-preview {
  width: 100%;
  height: 100%;
  position: relative;
  background-color: #f0f0f0;
}

.preview-content {
  width: 100%;
  height: 100%;
  object-fit: cover;
}

.video-preview video {
  pointer-events: none; /* 防止视频可点击播放 */
}

.play-icon {
  position: absolute;
  top: 50%;
  left: 50%;
  transform: translate(-50%, -50%);
  color: white;
  font-size: 24px;
  background: rgba(0, 0, 0, 0.45);
  border-radius: 50%;
  padding: 8px;
}

.media-actions {
  position: absolute;
  top: 0;
  right: 0;
  display: flex;
  gap: 4px;
  padding: 4px;
  background: rgba(0, 0, 0, 0.45);
  border-bottom-left-radius: 8px;
  opacity: 0;
  transition: opacity 0.3s;
}

.media-item:hover .media-actions {
  opacity: 1;
}

.action-icon {
  color: white;
  font-size: 16px;
  cursor: pointer;
  padding: 4px;
}

:deep(.ant-upload-drag) {
  height: auto;
  min-height: 104px;
}

:deep(.ant-upload-list) {
  display: none;
}

.tags-wrapper {
  display: flex;
  flex-wrap: wrap;
  gap: 8px;
  align-items: center;
}
</style>
